/**
 * 键盘事件
 */
import Editor from "../editor"
import isHotkey from 'is-hotkey'

export class KeyboardEvent {
    private isComposing: boolean = false
    constructor(private editor: Editor, private container: HTMLElement) {
        this.editor = editor
        this.container = container
        this.isComposing = false
    }

    compositionStartHandler_(e: CompositionEvent) {
        this.isComposing = true
    }

    compositionEndHandler_(e: CompositionEvent) {
        this.isComposing = false
        const text = e.data;
        if (text) {
            this.editor.insertTextAtCursor(text);
        }
    }

    private beforeInputHandler_(e: InputEvent) {
        const inputType = e.inputType;
        if (inputType === 'insertCompositionText' || inputType === 'deleteCompositionText') return
        e.preventDefault(); //阻止默认的输入显示
        switch (inputType) {
            case 'insertText':
                const text = e.data
                // 在光标位置插入文本
                if (text) {
                    this.editor.insertTextAtCursor(text);
                }
                break;
            case 'insertParagraph':
                this.editor.insertTextAtCursor("\n")
                break;
            case 'deleteContentBackward':
                this.editor.deleteTextAtCursor()
                break;
            case 'insertFromPaste':
                const data = e.dataTransfer?.getData('text/plain');
                if (data) {
                    this.editor.insertTextAtCursor(data);
                }
                break;
            //   brcase 'historyUndo':
            //     this.undoHandler()
            //     break;
            // case 'historyRedo':
            //     this.redoHandler()
            //   eak;

        }
    }
    keydownHandler_(e: any) {
        // 撤销
        if (isHotkey('mod+z')(e)) {
            e.preventDefault()
            this.editor.undo();
        }

        // 回退
        if (isHotkey('mod+y')(e)) {
            e.preventDefault()
            this.editor.redo?.();
        }
    }

    addListeners() {
        this.container.addEventListener('beforeinput', this.beforeInputHandler_.bind(this))
        this.container.addEventListener('keydown', this.keydownHandler_.bind(this))
        this.container.addEventListener('compositionstart', this.compositionStartHandler_.bind(this))
        this.container.addEventListener('compositionend', this.compositionEndHandler_.bind(this))
    }
}